using System;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.Caching;
using System.IO.Compression;
using System.ComponentModel;



namespace DalatCooking.Core.Web.HttpHandlers
{
    public class CssHandler : IHttpHandler
    {

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        private const string CSS_CACHE_BODY = "Css.FileBody";
        public void ProcessRequest(HttpContext context)
        {
           
            
                CompressionCss(context);
                // WriteCompressedFile(context, cssFile + Extensions.CSS, Folders.CSS);
            
        }
        private readonly string _commentRegEx = @"(//[^\n]*|(/\*(.|[\r\n])*?\*/))";
        private readonly string _quotedRegEx = @"(""((?:[^""\\\r\n]|\\.)*)""|'((?:[^'\\\r\n]|\\.)*)')";
        public const char DELIMITER = ',';
        private void CompressionCss(HttpContext context)
        {
            try
            {
                int cssLenght = context.Request.PhysicalPath.Length;
                string file = context.Request.PhysicalPath;
                if (!File.Exists(file))
                    return;
                int cacheTime = 300;
                string body = string.Empty;

                if (context.Cache[CSS_CACHE_BODY + file] != null)
                    body = context.Cache[CSS_CACHE_BODY + file].ToString();

                if (body == string.Empty)
                {
                    StreamReader reader = new StreamReader(file);
                    body = reader.ReadToEnd();
                    reader.Close();

                    body = StripComments(body);
                    body = body.Replace("  ", " ");
                    body = body.Replace(Environment.NewLine, String.Empty);
                    body = body.Replace("\t", string.Empty);
                    body = body.Replace(" {", "{");
                    body = body.Replace(" :", ":");
                    body = body.Replace(": ", ":");
                    body = body.Replace(", ", ",");
                    body = body.Replace("; ", ";");
                    body = body.Replace(";}", "}");

                    // sometimes found when retrieving CSS remotely
                    body = body.Replace(@"?", string.Empty);

                    // body = Regex.Replace(body, @"/\*[^\*]*\*+([^/\*]*\*+)*/", "$1");
                    body = Regex.Replace(body, @"(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?=&nbsp;)|(?<=&ndsp;)\s{2,}(?=[<])", String.Empty);

                    // Remove comments from CSS
                    body = Regex.Replace(body, @"/\*[\d\D]*?\*\n\t\r/", string.Empty);
                   // body += cssLenght;
                  //  body = Regex.Replace(body, _quotedRegEx, String.Empty);
                    CacheDependency cd = new CacheDependency(file);
                    context.Cache.Insert(CSS_CACHE_BODY + file, body, null, DateTime.Now.AddYears(cacheTime), TimeSpan.Zero);
                }

                context.Response.ContentType = "text/css";
                context.Response.Write(body);
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
        }
         private string StripComments(string body)
        {
           // body = Regex.Replace(body, @"/\*.+?\*/", "", RegexOptions.Singleline);
            body = Regex.Replace(body, _commentRegEx, "", RegexOptions.Singleline);
            return body;
        }

        #endregion
    }
}